#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2021/6/8
# @Author    :zhangxuchuo
# @Email     :zhangxuchuo@bbdservice.com
# @File      :EC66_EntUnsettledDistribution
# @Software  :PyCharm


'''eof
name:申请企业未结清借贷业务种类余额占比分布
code:EC66_EntUnsettledDistribution
tableName:
columnName:
groups:企业征信模块
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import re
import sys
import datetime
import pandas as pd

# reload(sys)
# sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--', []]


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
    '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def isFloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date

# 1.征信报告未结清借贷业务余额：TotalBalance = 信用提示信息单元(EB01)·信贷交易提示信息段(EB01A)·借贷交易余额(EB01AJ01)
# 业务种类池 =  [10-企业债 11-贷款 12-贸易融资 13-保理融资 14-融资租赁 15-证券类融资 16-透支 21-票据贴现 31-黄金借贷 41-垫款 51-资产处置 ]
# 2.对担保种类池循环，其中第i次循环时取第i个元素横杠前的数值部分，如"10","11"，记该数值为k：
# 3.令bal_i = [0]。对 对 借贷账户信息单元(ED01)中所有基本信息段(ED01A)做循环，并进行判断：
# {
# 判断1. 账户活动状态是否为未结清：账户活动状态(ED01AD01) IN [1-未结清]
# 判断2：担保种类是否满足：IF 基本信息段(ED01A)·借贷业务种类大类(ED01AD05)==k：业务大类满足
# }
# 4.如贷款账户同时满足[判断1:账户活动状态是否为未结清]、[判断2:业务大类满足]，则将对应的还款表现信息段(ED01B)·余额(ED01BJ01)放入bal_i
# 5.Factor_i = SUM(bal_i)
# 6.结束循环，将本次循环结果存入字典Dict_bal。Dict_bal = {"业务种类池[k]":"Factor_k"}, k = "1", "2", ...
# 8.字典Dict_bal_ratio与Dict_bal的key一样，value为Dict_bal的value除以TotalBalance
# 9.Factor = [Dict_bal, Dict_bal_ratio]
all_type = {'10':'10-企业债', '11':'11-贷款', '12':'12-贸易融资', '13':'13-保理融资', '14':'14-融资租赁', '15':'15-证券类融资', '16':'16-透支', '21':'21-票据贴现', '31':'31-黄金借贷', '41':'41-垫款', '51':'51-资产处置'}
def EC66_EntUnsettledDistribution():
    types = ['10','11','12','13','14','15','16','21','31','41','51']
    data = EC_DSJ_2D.get('data')
    #EBA 借贷账户信息 [1..1]
    EBA = getTable(data, 'EBA', 1, 1)
    if EBA == [{}]:
        return '缺失值'
    elif EBA == 0:
        return 0
    else:
        #EB01 信用提示信息单元 [0..1]
        EB01 = getTable(EBA[0], 'EB01', 1, 0)
        if EB01 == [{}]:
            return '缺失值'
        elif EB01 == 0:
            return 0
        else:
            #EB01A 信贷交易提示信息段 [0..1]
            EB01A = getTable(EB01[0], 'EB01A', 0, 1)
            if EB01A == [{}]:
                return '缺失值'
            elif EB01A == 0:
                return 0
            else:
                EB01AJ01 = EB01A[0].get('EB01AJ01')
                if isFloat(EB01AJ01) and float(EB01AJ01) > 0:
                    pass
                else:
                    return '缺失值'

    #EDA 借贷账户信息 [1..1]
    EDA = getTable(data, 'EDA', 1, 0)
    if EDA == [{}]:
        return '缺失值'
    elif EDA == 0:
        return 0
    else:
        # ED01 借贷账户信息单元 [0..*]
        ED01 = getTable(EDA[0], 'ED01', 0, 1)
        if ED01 == [{}]:
            return '缺失值'
        elif ED01 == 0:
            return 0
        else:
            Dict_bal = {}
            for Type in types:
                bal_i = [0]
                for i in ED01:
                    #ED01A 基本信息段 [1..1]
                    ED01A = getTable(i, 'ED01A', 1, 1)
                    #ED01B 还款表现信息段 [1..1]
                    ED01B = getTable(i, 'ED01B', 1, 1)
                    if ED01A == [{}] or ED01B == [{}]:
                         Dict_bal.update({all_type[Type]:sum(bal_i)})
                    elif ED01A == 0 or ED01B == 0:
                         Dict_bal.update({all_type[Type]:sum(bal_i)})
                    else:
                        #ED01AD01 账户活动状态 [1..1]
                        ED01AD01 = ED01A[0].get('ED01AD01')
                        #ED01AD05 借贷业务种类大类 [1..1]
                        ED01AD05 = ED01A[0].get('ED01AD05')
                        if ED01AD01 not in null_type_list and ED01AD05 not in null_type_list:
                            if ED01AD05 == Type and ED01AD01 == '1':
                                #ED01BH  还款表现信息 [0..*]
                                ED01BH = getTable(ED01B[0], 'ED01BH', 0, 1)
                                if ED01BH == [{}] or ED01BH == 0:
                                    Dict_bal.update({all_type[Type]:sum(bal_i)})
                                else:
                                    for i in ED01BH:
                                        #ED01BJ01 余额 [1..1]
                                        ED01BJ01 = i.get('ED01BJ01')
                                        if isFloat(ED01BJ01):
                                            bal_i.append(float(ED01BJ01))
                Dict_bal.update({all_type[Type]:sum(bal_i)})
    Dict_bal_ratio = {}
    [Dict_bal_ratio.update({all_type[i]:Dict_bal[all_type[i]] / float(EB01AJ01)}) for i in types]
    return json.dumps({'Dict_bal': Dict_bal, 'Dict_bal_ratio': Dict_bal_ratio}, ensure_ascii=False)








if __name__ == '__main__':
    with open(r'C:\Users\zdr\Desktop\samples\EC_DSJ_2D.json') as ff:
        EC_DSJ_2D = json.loads(ff.read())
    result = EC66_EntUnsettledDistribution()
    print(result)
result = EC66_EntUnsettledDistribution()
